package sourceagile.server.subversionFileRepository.specification;

import java.io.ByteArrayInputStream;

import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.io.ISVNEditor;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.diff.SVNDeltaGenerator;

import sourceagile.server.subversionFileRepository.SubversionRepositoryConnection;

/**
 * 
 * @Feature
 */
public class SaveSpecificationFile {

	public static void save(String repositoryURL, String username,
			String password, String fileName, String newFileContent) {

		SVNRepository repository;

		try {

			repository = SubversionRepositoryConnection.connect(repositoryURL,
					username, password);

			String logMessage = "Creating file: " + fileName;

			ISVNEditor repositoryEditor = repository.getCommitEditor(
					logMessage, null);

			repositoryEditor.openRoot(-1);

			try {

				repositoryEditor.addFile(fileName, null, -1);

			} catch (Exception e) {

				repositoryEditor.openFile(fileName, -1);
			}

			repositoryEditor.applyTextDelta(fileName, null);

			SVNDeltaGenerator deltaGenerator = new SVNDeltaGenerator();
			String checksum = deltaGenerator.sendDelta(fileName,
					new ByteArrayInputStream(newFileContent.getBytes()),
					repositoryEditor, true);

			repositoryEditor.closeFile(fileName, checksum);

			repositoryEditor.closeDir();

			repositoryEditor.closeEdit();

		} catch (SVNException e) {

			e.printStackTrace();

		}
	}
}
